﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MKAdmin.DataHelper;
using MKAdmin.DTO.Web.Common;
using MKAdmin.DTO.Web.Login;
using MKAdmin.IService.Web.Login;
using MKAdmin.ToolKit;

namespace MKAdmin.ServiceImpl.Web.Login
{
    public class LoginService : ILoginService
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public Result<UserInfoModel> UserLogin(LoginInfoParameter parameter)
        {
            var result = new Result<UserInfoModel>()
            {
                status = false,
                data = new UserInfoModel()
            };
            using (var util = new DBHelper())
            {
                string sql = @"SELECT top 1 oi.OperatorId OperatorId,oi.OperatorNo,oi.OperatorName
                                FROM DBO.OperatorInfo oi With(NoLock)
                               Where oi.OperatorNo = @OperatorNo And oi.OperatorPwd = @OperatorPwd
                                    And oi.StatusCode = 0";

                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(new SqlParameter() { ParameterName = "@OperatorNo", DbType = DbType.String, Value = parameter.OperatorNo });
                param.Add(new SqlParameter() { ParameterName = "@OperatorPwd", DbType = DbType.String, Value = SecurityHelper.Encrypt(parameter.OperatorPwd) });

                UserInfoModel obj = util.GetDataTable(sql, CommandType.Text, param.ToArray()).ToInfo<UserInfoModel>();
                if (obj != null && obj.OperatorId > 0)
                {
                    result.status = true;
                    result.data = obj;
                }
            }

            return result;
        }

        /// <summary>
        /// 用户登录日志
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public Result UserLoginLog(string operatorNo, bool loginStatus)
        {
            var result = new Result();

            using (var util = new DBHelper())
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"Insert Into dbo.LoginLog(OperatorNo,LoginStatus,IPAddress,LoginTime)
                                  Values(@OperatorNo,@LoginStatus,@IPAddress,GetDate())");

                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(new SqlParameter() { ParameterName = "@OperatorNo", DbType = DbType.String, Value = operatorNo });
                param.Add(new SqlParameter() { ParameterName = "@LoginStatus", DbType = DbType.Boolean, Value = loginStatus });
                param.Add(new SqlParameter() { ParameterName = "@IPAddress", DbType = DbType.String, Value = IpAddressHelper.GetIpAddress().data });

                util.ExecuteQuery(sql.ToString(), CommandType.Text, param.ToArray());

                return result;
            }
        }

        /// <summary>
        /// 验证用户状态
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public Result<UserInfoModel> VerifyUserStatus(UserInfoModel userInfo)
        {
            var result = new Result<UserInfoModel>()
            {
                status = false,
                data = new UserInfoModel()
            };
            using (var util = new DBHelper())
            {
                string sql = @"SELECT OperatorId
                                FROM DBO.OperatorInfo With(NoLock)
                               Where OperatorId = @OperatorId And StatusCode = 0";

                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(new SqlParameter() { ParameterName = "@OperatorId", DbType = DbType.Int32, Value = userInfo.OperatorId });

                UserInfoModel obj = util.GetDataTable(sql, CommandType.Text, param.ToArray()).ToInfo<UserInfoModel>();
                if (obj != null && obj.OperatorId > 0)
                {
                    result.status = true;
                    result.data = obj;
                }
            }

            return result;
        }

        /// <summary>
        /// 获取用户账号和下级账号列表('mk','mk001','mk002')
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public Result<List<AgentAccountModel>> GetMainAndSubAccountList(GetSubAccountParameter parameter)
        {
            var result = new Result<List<AgentAccountModel>>()
            {
                data = new List<AgentAccountModel>()
            };
            using (var util = new DBHelper())
            {
                //获取子账号
                string sql = $@"
                                With agentUser As(
                                 Select * From [Tb_mt_AgentUser] Where id = {parameter.AgentId}
                                 union all 
                                 select mtUser.* from agentUser,[Tb_mt_AgentUser] mtUser 
                                 where agentUser.Id = mtUser.ParentId
                                )
                                select Id AgentId,AgentName,RealName,TypeCode,ParentId from agentUser 
                                Where (TypeCode IN (1,2) Or Id = {parameter.AgentId}) 
                                        And AccountStatusCode IN({getAccountStatusFlag(parameter.AccountStatusCode)})
                            ";

                DataTable dtList = util.GetDataTable(sql);

                if (dtList != null && dtList.Rows.Count > 0)
                {
                    result.data = dtList.ToList<AgentAccountModel>();
                }
            }

            return result;
        }

        /// <summary>
        /// 获取客服账号列表('chat001','chat002','chat003')
        /// </summary>
        /// <returns></returns>
        public Result<List<AgentAccountModel>> GetKfAccountList(GetSubAccountParameter parameter)
        {
            var result = new Result<List<AgentAccountModel>>()
            {
                data = new List<AgentAccountModel>()
            };
            using (var util = new DBHelper())
            {
                string sql = $@"
                                With agentUser As(
                                 Select * From [Tb_mt_AgentUser] Where id = {parameter.AgentId}
                                 Union All 
                                 select mtUser.* from agentUser,[Tb_mt_AgentUser] mtUser 
                                 where agentUser.Id = mtUser.ParentId
                                )
                                select Id AgentId,AgentName,RealName,TypeCode,ParentId from agentUser 
                                Where (TypeCode = 3 Or Id = {parameter.AgentId}) 
                                    And AccountStatusCode IN({getAccountStatusFlag(parameter.AccountStatusCode)})
                              ";

                DataTable dtList = util.GetDataTable(sql);
                if (dtList != null && dtList.Rows.Count > 0)
                {
                    result.data = dtList.ToList<AgentAccountModel>();
                }
            }

            return result;
        }

        /// <summary>
        /// 获取当前超级管理员下账号列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public Result<List<AgentAccountModel>> GetAccountList(GetAccountListParameter parameter)
        {
            var result = new Result<List<AgentAccountModel>>()
            {
                data = new List<AgentAccountModel>()
            };
            using (var util = new DBHelper())
            {
                //先获取当前登录账号超级管理账号
                int supperiorId = 0;
                string supperiorSql = $@"
                            Declare @SuperiorId Int;
                            With agentUser As(
                                Select * From [Tb_mt_AgentUser] Where id = {parameter.AgentId}
                                Union All 
                                Select mtUser.* from agentUser,[Tb_mt_AgentUser] mtUser 
                                   Where agentUser.ParentId = mtUser.Id
                                )
                                Select Top 1 @SuperiorId = Id from agentUser 
                                Where TypeCode = 10
                            SELECT @SuperiorId";
                object supperiorObj = util.ExecuteScalar(supperiorSql);
                if (supperiorObj != null)
                {
                    supperiorId = Convert.ToInt32(supperiorObj);
                }

                //获取超级管理员下级账号信息
                string sql = $@"
                                With agentUser As(
                                  Select * From [Tb_mt_AgentUser] Where id = {supperiorId}
                                Union All 
                                Select mtUser.* from agentUser,[Tb_mt_AgentUser] mtUser 
                                Where agentUser.Id = mtUser.ParentId
                                )
                                Select Id AgentId,AgentName,RealName,TypeCode,ParentId from agentUser 
                                    Where (TypeCode IN({getAccountTypeFlag(parameter.AccountTypeCode)}) 
                                            Or Id = {supperiorId})
                                            And AccountStatusCode IN({getAccountStatusFlag(parameter.AccountStatusCode)})
                              ";

                DataTable dtList = util.GetDataTable(sql);
                if (dtList != null && dtList.Rows.Count > 0)
                {
                    result.data = dtList.ToList<AgentAccountModel>();
                }
            }

            return result;
        }

        /// <summary>
        /// 获取状态标识
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private string getAccountStatusFlag(EmAccountStatusCode statusCode)
        {
            string accountStatus = "0";
            if (statusCode == EmAccountStatusCode.ForbiddenOnly)
            {
                accountStatus = "1";
            }
            else if (statusCode == EmAccountStatusCode.NorAndForbidden)
            {
                accountStatus = "0,1";
            }
            else if (statusCode == EmAccountStatusCode.All)
            {
                accountStatus = "0,1,2";
            }

            return accountStatus;
        }

        /// <summary>
        /// 获取类型标识
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private string getAccountTypeFlag(EmAccountTypeCode typeCode)
        {
            string accountType = "10";
            switch (typeCode)
            {
                case EmAccountTypeCode.Superior:
                    accountType = "10";
                    break;
                case EmAccountTypeCode.First:
                    accountType = "1";
                    break;
                case EmAccountTypeCode.Second:
                    accountType = "2";
                    break;
                case EmAccountTypeCode.Service:
                    accountType = "3";
                    break;
                case EmAccountTypeCode.Manager:
                    accountType = "10,1,2";
                    break;
                case EmAccountTypeCode.All:
                    accountType = "10,1,2,3";
                    break;
                default:
                    break;
            }

            return accountType;
        }
    }
}
